<template>
  <div class="collection-list">
    <div class="search-bar">
      <a-input-search
        v-model:value="collectionQueryParams.title"
        placeholder="搜索合集标题"
        enter-button
        @search="handleSearch"
        style="width: 200px"
      />
    </div>

    <div
      class="collection-list-container"
      v-if="collectionList.length > 0 || collectionQueryParams.userId == userStore.getUserId"
    >
      <div class="container-list">
        <div
          class="collection-list-item"
          v-for="item in collectionList"
        >
          <div class="collection-list-item-content">
            <div class="collection-list-item-cover">
              <div
                v-if="item.thumbnailUrl && item.isVisible == 1"
                class="cover-image"
                @click="handleDetail(item.id)"
              >
                <a-image
                  shape="square"
                  :src="item.thumbnailUrl"
                  size="large"
                  :preview="false"
                  style="width: 200px; height: 150px; cursor: pointer"
                />
              </div>
              <div
                v-else
                class="no-video"
              >
                {{ item.isVisible == 1 ? '暂无视频' : '已隐藏' }}
              </div>
              <div class="cover-count">
                {{ item.videoIdList?.length || 0 }}
              </div>
            </div>
            <div class="collection-list-item-title">
              <span
                class="item-title"
                @click="handleDetail(item.id)"
                >{{ item.title }}</span
              >
              <a-dropdown
                placement="bottom"
                v-if="collectionQueryParams.userId == userStore.getUserId"
              >
                <a
                  class="ant-dropdown-link"
                  @click.prevent
                >
                  <a-button style="height: 30px">更多</a-button>
                </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item>
                      <a-button
                        type="link"
                        @click="handleEdit(item)"
                      >
                        编辑
                      </a-button>
                    </a-menu-item>

                    <a-menu-item>
                      <a-button
                        type="link"
                        danger
                        @click="handleDelete(item.id)"
                      >
                        删除
                      </a-button>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
          </div>
        </div>

        <div
          v-if="collectionQueryParams.userId == userStore.getUserId"
          class="add-collection-button"
          @click="dialogVisible = true"
        >
          <div class="add-button-container">
            <div class="add-button">
              <PlusOutlined />
            </div>
          </div>
        </div>
      </div>

      <Pagination
        style="margin-top: 150px"
        v-model:page="collectionQueryParams.pageNo"
        v-model:limit="collectionQueryParams.pageSize"
        :total="collectionListTotal"
        @pagination="getCollectionList"
      />
    </div>

    <div
      style="width: 100%"
      v-else
    >
      <a-empty />
    </div>
  </div>

  <teleport to="body">
    <a-modal
      v-model:visible="dialogVisible"
      :title="isEdit ? '编辑合集' : '创建合集'"
      width="50%"
      :zIndex="1050"
      :centered="true"
      :keyboard="false"
      :mask-closable="false"
      :body-style="{ padding: '20px' }"
      @cancel="handleOnClose"
    >
      <a-form
        :model="form"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item
          label="标题"
          name="title"
        >
          <a-input
            v-model:value="form.title"
            maxlength="20"
            show-count
            placeholder="请输入合集标题"
          />
        </a-form-item>

        <a-form-item
          label="描述"
          name="description"
        >
          <a-textarea
            v-model:value="form.description"
            maxlength="500"
            show-count
            placeholder="请输入合集描述"
            :rows="4"
          />
        </a-form-item>

        <a-form-item
          label="是否可见"
          name="isVisible"
        >
          <a-switch
            v-model:checked="form.isVisible"
            :checked-value="1"
            :un-checked-value="0"
            checked-children="公开"
            un-checked-children="隐藏"
          />
        </a-form-item>

        <a-button @click="handleOpenRefDialog(form.id)">
          关联视频（已关联 {{ form.videoIdList?.length || '0' }} 个视频）
        </a-button>
      </a-form>

      <template #footer>
        <div style="text-align: right">
          <a-button
            key="back"
            @click="handleOnClose"
          >
            取消
          </a-button>

          <a-button
            key="submit"
            type="primary"
            @click="handleSubmit"
          >
            {{ isEdit ? '保存' : '创建' }}
          </a-button>
        </div>
      </template>
    </a-modal>
  </teleport>

  <teleport to="body">
    <a-modal
      v-model:visible="collectionDetailDialogVisible"
      title="合集详情"
      width="90%"
      :zIndex="1050"
      :centered="true"
      :keyboard="false"
      :mask-closable="false"
      :body-style="{ padding: '20px' }"
      @cancel="handleOnClose"
    >
      <!-- 功能：有点像帖子的类型：左边是合集的标题和简介，右边则是视频数据 -->
      <div class="collection-detail-container">
        <div class="collection-detail-left">
          <div class="collection-detail-title">
            {{ collectionDetailResp.title }}
          </div>
          <div class="collection-detail-description">
            {{ collectionDetailResp.description }}
          </div>
        </div>
        <div class="collection-detail-right">
          <div class="collection-detail-header">
            <div class="collection-detail-header-title">
              <a-input-search
                v-model:value="collectionDetailQueryPrams.title"
                placeholder="按标题查找视频"
                enter-button
                @search="handleVideoSearch"
                style="max-width: 300px"
              />
            </div>
          </div>

          <div
            v-if="
              collectionDetailResp.videoList?.list &&
              collectionDetailResp.videoList?.list.length > 0
            "
            style="display: flex; flex-wrap: wrap"
          >
            <div
              class="collection-detail-item"
              v-for="item in collectionDetailResp.videoList.list"
              :key="item.id"
            >
              <div class="collection-detail-item-container">
                <div class="collection-detail-item-cover">
                  <img
                    :src="item.thumbnailUrl"
                    alt="视频缩略图"
                    @click="locateToVideoPage(item.id)"
                  />
                </div>

                <a-button
                  type="link"
                  class="collection-detail-item-title"
                  :title="item.title"
                  @click="locateToVideoPage(item.id)"
                >
                  <strong>{{ item.title }}</strong>
                </a-button>
              </div>
            </div>

            <Pagination
              v-if="collectionDetailResp.videoList.total > collectionDetailQueryPrams.pageSize"
              style="margin-top: 30px"
              v-model:page="collectionDetailQueryPrams.pageNo"
              v-model:limit="collectionDetailQueryPrams.pageSize"
              :total="collectionDetailResp.videoList.total"
              @pagination="handleDetail(collectionDetailResp.id)"
            />
          </div>

          <div v-else>
            <a-empty />
          </div>
        </div>
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button
            key="back"
            @click="handleDetailDialogClose"
          >
            关闭
          </a-button>
        </div>
      </template>
    </a-modal>
  </teleport>

  <teleport to="body">
    <a-modal
      v-model:visible="refDialog"
      title="关联视频"
      width="90%"
      :zIndex="1050"
      :centered="true"
      :keyboard="false"
      :mask-closable="false"
      :body-style="{ padding: '20px' }"
      @ok="handleRefDialogConfirm"
      @cancel="handleRefDialogClose"
    >
      <!-- 视频列表 -->
      <div
        class="ref-list"
        v-if="refList.length > 0"
      >
        <div class="ref-list-header">
          <div class="ref-list-title">
            <a-input-search
              v-model:value="refQueryParams.title"
              placeholder="按标题查找视频"
              enter-button
              @search="handleRefSearch"
              style="max-width: 300px"
            />
          </div>
        </div>

        <div
          v-for="video in refList"
          :key="video.id"
          class="ref-item"
          @click="handleRefItemClick(video)"
        >
          <a-checkbox
            :checked="video.selected"
            class="ref-checkbox"
          />
          <a-image
            :width="120"
            :height="80"
            :src="video.thumbnailUrl"
            :preview="false"
            class="ref-cover"
          />
          <div class="ref-info">
            <div class="ref-title">{{ video.title }}</div>
            <div class="ref-stats">
              <span class="stat-item">
                <EyeOutlined />
                {{ formatNumber(video.viewCount) }}
              </span>
              <span class="stat-item">
                <CalendarOutlined />
                {{ timeFormat(video.publishTime) }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <Pagination
        style="margin-top: 20px"
        v-if="refList.length > 0"
        v-model:page="refQueryParams.pageNo"
        v-model:limit="refQueryParams.pageSize"
        :total="refTotal"
        @pagination="getRefList"
      />

      <div v-else>
        <a-empty />
      </div>
    </a-modal>
  </teleport>
</template>

<script setup lang="ts">
import type {
  CvVideoCollectionDetailPageReqVO,
  CvVideoCollectionDetailRespVO,
  CvVideoCollectionPageReqVO,
  CvVideoCollectionRespVO,
  CvVideoCollectionSaveReqVO
} from '@/types/collection'
import { useUserStore } from '@/store/modules/user'
import { EyeOutlined, PlusOutlined, CalendarOutlined } from '@ant-design/icons-vue'
import {
  createCollection,
  deleteCollection,
  getCollection,
  updateCollection
} from '@/api/collection'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import { CvVideoUncollectedReqVO, CvVideoUncollectedRespVO } from '@/types/video'
import { getUncollectedVideoPage, getUncollectedVideoPageAndCurrent } from '@/api/video'

const emit = defineEmits(['getList'])

const userStore = useUserStore()

const collectionList = defineModel<CvVideoCollectionRespVO[]>()
const collectionQueryParams = defineModel<CvVideoCollectionPageReqVO>('queryParams')
const collectionListTotal = defineModel('total')

const dialogVisible = ref(false)

/**
 * 获取合集列表
 */
const getCollectionList = async () => {
  emit('getList')
}

/**
 * 处理搜索
 */
const handleSearch = () => {
  collectionQueryParams.value.pageNo = 1
  getCollectionList()
}

/**
 * 合集表单
 */
const formRef = ref()
const form = reactive<CvVideoCollectionSaveReqVO>({
  id: null,
  userId: userStore.getUserId,
  title: '',
  description: '',
  isVisible: 1,
  videoIdList: []
})

const rules = {
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'blur'
    }
  ]
}

/**
 * 创建/编辑合集
 */
const isEdit = ref(false)
const handleSubmit = () => {
  if (!formRef.value) {
    return
  }

  formRef.value
    .validate()
    .then(async () => {
      const res = isEdit.value ? await updateCollection(form) : await createCollection(form)
      if (res) {
        dialogVisible.value = false
        await getCollectionList()
        message.success(isEdit.value ? '编辑成功' : '创建成功')
        handleOnClose()
      }
    })
    .catch(error => {})
}

/**
 * 对话框关闭事件
 */
const handleOnClose = () => {
  dialogVisible.value = false
  formRef.value.resetFields()
  form.id = null
  form.videoIdList = []
}

/**
 * 编辑合集
 */
const handleEdit = (item: CvVideoCollectionRespVO) => {
  isEdit.value = true
  form.id = item.id
  form.title = item.title
  form.description = item.description
  form.isVisible = item.isVisible
  form.videoIdList = item.videoIdList
  dialogVisible.value = true
}

/**
 * 删除合集
 */
const handleDelete = (id: number) => {
  Modal.confirm({
    title: '确定要删除该合集吗？',
    content: '删除后无法恢复',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: async () => {
      await deleteCollection(id)
      await getCollectionList()
      message.success('删除成功')
    }
  })
}

/**
 * 合集详情
 */
const collectionDetailDialogVisible = ref(false)

const collectionDetailResp = ref<CvVideoCollectionDetailRespVO>()

const collectionDetailQueryPrams = ref<CvVideoCollectionDetailPageReqVO>({
  id: 0,
  title: '',
  pageNo: 1,
  pageSize: 10
})

/**
 * 查看详情
 */
const handleDetail = async (id: number) => {
  if (id) {
    collectionDetailQueryPrams.value.id = id
    collectionDetailResp.value = await getCollection(collectionDetailQueryPrams.value)
    collectionDetailDialogVisible.value = true
  }
}

/**
 * 查询视频
 */
const handleVideoSearch = () => {
  collectionDetailQueryPrams.value.pageNo = 1
  handleDetail(collectionDetailQueryPrams.value.id)
}

/**
 * 合集详情对话框关闭
 */
const handleDetailDialogClose = () => {
  collectionDetailResp.value = <CvVideoCollectionDetailRespVO>{
    id: 0,
    title: '',
    pageNo: 1,
    pageSize: 10
  }

  collectionDetailQueryPrams.value.id = 0
  collectionDetailQueryPrams.value.title = ''
  collectionDetailQueryPrams.value.pageNo = 1
  collectionDetailDialogVisible.value = false
}

/**
 * 关联视频
 */
const refDialog = ref(false)
const refList = ref<CvVideoUncollectedRespVO[]>([])
const refTotal = ref(0)

const refQueryParams = ref<CvVideoUncollectedReqVO>({
  collectionId: null,
  title: '',
  pageNo: 1,
  pageSize: 5
})

const handleOpenRefDialog = async (id: number = 0) => {
  if (isEdit.value && id !== 0) {
    refQueryParams.value.collectionId = id
  }
  await getRefList()
  refDialog.value = true
}

const handleRefSearch = () => {
  refQueryParams.value.pageNo = 1
  getRefList()
}

/**
 * 获取未关联和被当前合集关联的数据
 */
const getRefList = async () => {
  const res = isEdit.value
    ? await getUncollectedVideoPageAndCurrent(refQueryParams.value)
    : await getUncollectedVideoPage(refQueryParams.value)
  refList.value = res.list
  refTotal.value = res.total

  if (isEdit.value) {
    refList.value.forEach(item => {
      if (form.videoIdList.includes(item.id)) {
        item.selected = true
      }
    })
  }
}

/**
 * 选择事件
 */
const handleRefItemClick = (video: CvVideoUncollectedRespVO) => {
  refList.value.forEach(item => {
    if (item.id === video.id) {
      item.selected = !item.selected
    }
  })
}

/**
 * 关联视频确定事件
 */
const handleRefDialogConfirm = () => {
  form.videoIdList = refList.value
    .filter(item => item.selected)
    .map(item => {
      return item.id
    })
  handleRefDialogClose()
}

/**
 * 对话框关闭事件
 */
const handleRefDialogClose = () => {
  refDialog.value = false
  refList.value = []
  refQueryParams.value.title = ''
  refQueryParams.value.pageNo = 1
  refQueryParams.value.pageSize = 5
  refQueryParams.value.collectionId = null
  refTotal.value = 0
}

/**
 * 跳转到视频页
 */
const locateToVideoPage = (videoId: number) => {
  window.open(`/video?videoId=${videoId}`)
}

/**
 * 播放量格式化
 */
const formatNumber = (num: number) => {
  if (!num) {
    return 0
  }

  if (num >= 1000 && num < 10000) {
    return (num / 1000).toFixed(1) + 'K'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'W'
  } else {
    return num.toString()
  }
}

/**
 * 时间格式化
 */
const timeFormat = (time: string) => {
  if (time) {
    return dayjs(time).format('YYYY-MM-DD')
  }
  return ''
}
</script>

<style scoped>
.collection-list {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.search-bar {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  margin-bottom: 20px;
}

.add-collection-button {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  margin-bottom: 20px;
}

.add-button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
}

.add-button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  background-color: #1890ff;
  color: white;
  border-radius: 8px;
  font-size: 24px;
}

.collection-list-container {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.container-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: flex-start;
}

.collection-list-item,
.add-collection-button {
  width: 200px;
}

.collection-list-item-cover {
  width: 200px;
  height: 150px;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
}

.no-video {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  color: #999;
  border-radius: 8px;
}

.cover-count {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
}

.collection-list-item-title {
  height: 30px;
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.item-title {
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.item-title:hover {
  color: #1890ff;
}

.collection-detail-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.collection-detail-left {
  flex: 1;
  margin-right: 20px;
  border-right: 1px solid #e8e8e8;
}

.collection-detail-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.collection-detail-description {
  font-size: 16px;
  color: #555;
  width: 400px;
  height: 100%;
}

.collection-detail-right {
  flex: 2;
}

.collection-detail-header {
  margin-bottom: 20px;
}

.collection-detail-header-title {
  display: flex;
  justify-content: flex-end;
}

.collection-detail-item {
  width: 18%;
  margin: 10px;
}

.collection-detail-item img {
  width: 100%;
  border-radius: 8px;
  height: 120px;
  cursor: pointer;
}

.collection-detail-item-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.collection-detail-item-title {
  font-size: 15px;
  padding: 0;
  color: #000000;
  cursor: pointer;
}

.ref-list {
  max-height: 60vh;
  overflow-y: auto;
  margin-bottom: 20px;
}

.ref-list-header {
  text-align: right;
}

.ref-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
  cursor: pointer;
}

.ref-item:hover {
  background-color: #fafafa;
}

.ref-checkbox {
  margin-right: 16px;
}

.ref-cover {
  border-radius: 4px;
  overflow: hidden;
  margin-right: 16px;
}

.ref-info {
  flex: 1;
  margin-left: 30px;
}

.ref-title {
  font-size: 16px;
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.85);
}

.ref-stats {
  display: flex;
  gap: 20px;
  color: rgba(0, 0, 0, 0.45);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
